<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools>
        <span>本月: 发送双份奖金</span>
        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button type="danger" size="small" @click="handleExport">excel导出</el-button>
          <el-button type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </PageTools>
      <!-- 员工列表 -->
      <el-card style="margin-top: 10px;">
        <el-table :data="list" border>
          <el-table-column label="序号" type="index" sortable="" />
          <el-table-column label="姓名" prop="username" sortable="" />
          <el-table-column label="工号" prop="workNumber" sortable="" />

          <el-table-column label="聘用形式" sortable="">
            <template v-slot="{row}">
              {{ formHiretype(row.formOfEmployment) }}
            </template>
          </el-table-column>

          <el-table-column label="部门" prop="departmentName" sortable="" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable="">
            <template v-slot="{row}">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" prop="enableState" sortable="">
            <template v-slot="{row}">
              <el-switch v-model="row.enableState" :active-value="1" :inactive-value="2" />

            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template v-slot="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="assignRole(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="deladd(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <div style="height: 60px; margin-top: 10px">
          <el-pagination :page-size="queryParams.size" :current-page="queryParams.page" :total="total" layout="prev, pager, next" @current-change="currentChange" />
        </div>
      </el-card>
    </div>
    <!-- 添加员工组件弹框 -->
    <AddEmployee :show-dialog.sync="showDialog" />
    <!-- 分配角色组件弹框 -->
    <AssignRole :current-user-id="currentUserId" :show-role-dialog.sync="showRoleDialog" />
  </div>
</template>

<script>
import { reqGetEmployeeList, reqDelEmployee } from '@/api/employees'
import Types from '@/api/constant/employees.js'
import AddEmployee from '@/views/employees/components/AddEmployee.vue'
import AssignRole from '@/views/employees/components/AssignRole.vue'
import moment from 'moment'
export default {
  components: {
    AddEmployee, AssignRole
  },
  data () {
    return {
      // 当前分配角色的用户ID
      currentUserId: '',
      // 控制角色分配弹框
      showRoleDialog: false,
      // 控制添加员工弹窗标志位
      showDialog: false,
      // 聘用形式
      hireType: Types.hireType,
      // 列表总数
      total: 0,
      // 员工列表
      list: [],
      // 查询参数
      queryParams: {
        page: 1,
        size: 10
      }
    }
  },
  created () {
    this.loadEmpList()
  },
  methods: {
    // 分配角色
    assignRole (id) {
      this.currentUserId = id
      this.showRoleDialog = true
    },
    // 把后端返回的员工数据转换为Excel需要的格式
    translateData (list) {
      const result = {
        title: [],
        data: []
      }
      const headers = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      // 生成导出的表头信息 Object.keys会把对象中的键生成一个数组
      // result.title = ['姓名', '手机号',....]
      result.title = Object.keys(headers)

      // 转换原始的员工列表数据
      list.forEach(item => {
        // 每次遍历应该生成一行数据
        const row = []
        // 生成每一行数据项
        result.title.forEach(tname => {
          // 找出headers中的每一项的值
          const enKey = headers[tname]
          // 根据遍历的item找出对应的数据
          let value = item[enKey]
          // 处理特殊的值
          if (enKey === 'formOfEmployment') {
            // 聘用形式
            const info = Types.hireType.find(item => item.id === Number(value))
            if (info) {
              value = info.value
            } else {
              value = '其他'
            }
          } else if (['timeOfEntry', 'correctionTime'].includes(enKey)) {
            // 处理时间格式
            try {
              value = moment(value).format('yyyy-MM-DD')
            } catch (err) {
              // console.log(err)
              value = '无效日期'
            }
          }
          // 把数据添加到row中
          row.push(value)
        })
        // 把一个员工的数据放到最终的二维数组中
        result.data.push(row)
      })

      return result
    },
    // 导出员工信息
    async handleExport () {
      // 获取需要导出的员工列表数据
      const ret = await reqGetEmployeeList({ page: 1, size: 100 })
      console.log(ret)
      // 把员工的数据转换为二位数组
      const result = this.translateData(ret.data.rows)

      // import导入的文件称之为：按需加载(webpack)
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          // 表头 必填
          header: result.title,
          // 具体数据 必填
          data: result.data,
          // 下载的文件名称
          filename: 'excel-list',
          // 列宽是否自动
          autoWidth: true,
          // 文件后缀名称
          bookType: 'xlsx'
        })
      })
    },
    async loadEmpList () {
      const ret = await reqGetEmployeeList(this.queryParams)
      if (ret.code === 10000) {
        // console.log(ret)
        this.total = ret.data.total
        this.list = ret.data.rows
      }
    },
    // 监听页码的变化
    currentChange (page) {
      this.queryParams.page = page
      this.loadEmpList()
    },
    // 格式化聘用形式
    formHiretype (formOfEmployment) {
      // console.log(formOfEmployment)
      const info = this.hireType.find(item => parseInt(item.id) === parseInt(formOfEmployment))
      if (info) {
        return info.value
      } else {
        return '其他'
      }
    },
    // 删除员工
    async deladd (id) {
      const res = await this.$confirm('确认要删除员工吗？, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 点击取消
      if (res === 'cancel') return
      // 确认以后
      try {
        const ret = await reqDelEmployee(id)
        if (ret.code === 10000) {
          // 删除成功；刷新列表，提示信息
          this.loadEmpList()
          this.$message.success('删除员工成功')
        } else {
          this.$message.error(ret.message)
        }
      } catch {
        this.$message.error('删除员工失败')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
